package com.gcloud.api.condition;

import com.gcloud.api.ApiRole;
import com.gcloud.common.util.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.PropertyResolver;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
Copyright (c) [2020] [G-CLOUD TECHNOLOGY] [G-Cloud 8.0] is licensed under the Mulan PSL v1.
You can use this software according to the terms and conditions of the Mulan PSL v1. You may obtain
a copy of Mulan PSL v1 at: http://license.coscl.org.cn/MulanPSL THIS SOFTWARE IS PROVIDED ON AN 
"AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v1 for more details.
 */


@Order(Ordered.HIGHEST_PRECEDENCE + 20)
public class ApiRoleCondition extends SpringBootCondition{
	
	@Override
	public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
		// TODO Auto-generated method stub
		//String kvmServicePkg="com.gcloud.compute.service.kvm";
		Map<String, Object> attributes = metadata.getAnnotationAttributes(ApiRoleSelect.class.getName());
		if(attributes==null){
			return ConditionOutcome.noMatch("");
		}


		PropertyResolver resolver = context.getEnvironment();
		String roleConfig = resolver.getProperty(ApiRole.CONFIG_KEY);

		if(match(roleConfig, attributes)){
			return ConditionOutcome.match();
		}

		return ConditionOutcome.noMatch("");

	}

	public static boolean match(String roleConfig, Map<String, Object> attributes){
		if(StringUtils.isBlank(roleConfig)){
			return false;
		}

		if(attributes.get("value") == null){
			return false;
		}

		String[] values = (String[])attributes.get("value");
		List<String> componentRole = new ArrayList<>(Arrays.asList(values));
		List<String> configRole = new ArrayList<>(Arrays.asList(roleConfig.split(",")));


		componentRole.retainAll(configRole);
		//有交集，则为match
		if(componentRole.size() > 0){
			return true;
		}

		return false;
	}

}